const pool = require('../config/database');

class MedicationModel {
  /**
   * 创建用药记录
   * @param {Object} medicationData - 用药数据
   * @returns {Promise<Object>} 创建的用药记录
   */
  static async create(medicationData) {
    const connection = await pool.getConnection();
    
    try {
      await connection.beginTransaction();
      
      const fields = Object.keys(medicationData);
      const values = Object.values(medicationData);
      const placeholders = fields.map(() => '?').join(', ');
      
      const sql = `
        INSERT INTO jktj_medication (${fields.join(', ')})
        VALUES (${placeholders})
      `;
      
      const [result] = await connection.execute(sql, values);
      
      await connection.commit();
      
      return {
        id: result.insertId,
        ...medicationData
      };
    } catch (error) {
      await connection.rollback();
      throw error;
    } finally {
      connection.release();
    }
  }

  /**
   * 批量创建用药记录
   * @param {Array<Object>} medicationList - 用药数据数组
   * @returns {Promise<Array>} 创建的用药记录数组
   */
  static async createBatch(medicationList) {
    if (!medicationList || medicationList.length === 0) {
      return [];
    }

    const connection = await pool.getConnection();
    const results = [];
    
    try {
      await connection.beginTransaction();
      
      for (const medicationData of medicationList) {
        const fields = Object.keys(medicationData);
        const values = Object.values(medicationData);
        const placeholders = fields.map(() => '?').join(', ');
        
        const sql = `
          INSERT INTO jktj_medication (${fields.join(', ')})
          VALUES (${placeholders})
        `;
        
        const [result] = await connection.execute(sql, values);
        
        results.push({
          id: result.insertId,
          ...medicationData
        });
      }
      
      await connection.commit();
      return results;
    } catch (error) {
      await connection.rollback();
      throw error;
    } finally {
      connection.release();
    }
  }

  /**
   * 根据体检ID获取用药记录列表
   * @param {number} tjId - 体检ID
   * @returns {Promise<Array>} 用药记录列表
   */
  static async findByTjId(tjId) {
    const sql = 'SELECT * FROM jktj_medication WHERE tj_id = ? ORDER BY id';
    const [rows] = await pool.execute(sql, [tjId]);
    return rows;
  }

  /**
   * 根据ID获取用药记录
   * @param {number} id - 用药记录ID
   * @returns {Promise<Object>} 用药记录
   */
  static async findById(id) {
    const sql = 'SELECT * FROM jktj_medication WHERE id = ?';
    const [rows] = await pool.execute(sql, [id]);
    return rows[0] || null;
  }

  /**
   * 更新用药记录
   * @param {number} id - 用药记录ID
   * @param {Object} updateData - 更新数据
   * @returns {Promise<boolean>} 更新结果
   */
  static async update(id, updateData) {
    const fields = Object.keys(updateData);
    const values = Object.values(updateData);
    const setClause = fields.map(field => `${field} = ?`).join(', ');
    
    const sql = `UPDATE jktj_medication SET ${setClause} WHERE id = ?`;
    const [result] = await pool.execute(sql, [...values, id]);
    
    return result.affectedRows > 0;
  }

  /**
   * 删除用药记录
   * @param {number} id - 用药记录ID
   * @returns {Promise<boolean>} 删除结果
   */
  static async delete(id) {
    const sql = 'DELETE FROM jktj_medication WHERE id = ?';
    const [result] = await pool.execute(sql, [id]);
    return result.affectedRows > 0;
  }

  /**
   * 根据体检ID删除所有用药记录
   * @param {number} tjId - 体检ID
   * @returns {Promise<boolean>} 删除结果
   */
  static async deleteByTjId(tjId) {
    const sql = 'DELETE FROM jktj_medication WHERE tj_id = ?';
    const [result] = await pool.execute(sql, [tjId]);
    return result.affectedRows > 0;
  }

  /**
   * 批量获取多个体检的用药记录
   * @param {Array<number>} tjIds - 体检ID数组
   * @returns {Promise<Array>} 用药记录数组
   */
  static async findByTjIds(tjIds) {
    if (!tjIds || tjIds.length === 0) {
      return [];
    }
    
    const placeholders = tjIds.map(() => '?').join(', ');
    const sql = `
      SELECT * FROM jktj_medication 
      WHERE tj_id IN (${placeholders}) 
      ORDER BY tj_id, id
    `;
    const [rows] = await pool.execute(sql, tjIds);
    return rows;
  }

  /**
   * 根据药品名称搜索用药记录
   * @param {number} tjId - 体检ID
   * @param {string} drugName - 药品名称
   * @returns {Promise<Array>} 用药记录列表
   */
  static async findByDrugName(tjId, drugName) {
    const sql = `
      SELECT * FROM jktj_medication 
      WHERE tj_id = ? AND ypmc LIKE ?
      ORDER BY id
    `;
    const [rows] = await pool.execute(sql, [tjId, `%${drugName}%`]);
    return rows;
  }

  /**
   * 获取用药依从性统计
   * @param {number} tjId - 体检ID
   * @returns {Promise<Object>} 依从性统计
   */
  static async getComplianceStats(tjId) {
    const sql = `
      SELECT 
        ypfyycx,
        COUNT(*) as count
      FROM jktj_medication 
      WHERE tj_id = ?
      GROUP BY ypfyycx
    `;
    const [rows] = await pool.execute(sql, [tjId]);
    
    const stats = {
      total: 0,
      regular: 0,    // 规律
      irregular: 0,  // 间断
      none: 0        // 不服药
    };
    
    rows.forEach(row => {
      stats.total += row.count;
      switch (row.ypfyycx) {
        case '1':
          stats.regular = row.count;
          break;
        case '2':
          stats.irregular = row.count;
          break;
        case '3':
          stats.none = row.count;
          break;
      }
    });
    
    return stats;
  }

  /**
   * 获取剂量单位字典
   * @returns {Object} 剂量单位字典
   */
  static getDosageUnitDict() {
    return {
      '0': 'g',
      '1': 'mg',
      '2': 'ml',
      '3': '片',
      '4': '粒',
      '5': '支',
      '6': '瓶',
      '7': '盒'
    };
  }

  /**
   * 获取用药时间单位字典
   * @returns {Object} 用药时间单位字典
   */
  static getTimeUnitDict() {
    return {
      '1': '天',
      '2': '月',
      '3': '年'
    };
  }

  /**
   * 获取服药依从性字典
   * @returns {Object} 服药依从性字典
   */
  static getComplianceDict() {
    return {
      '1': '规律',
      '2': '间断',
      '3': '不服药'
    };
  }
}

module.exports = MedicationModel;